import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

smtp_server = 'smtp.exmail.qq.com'
from_addr = 'lideping@sxtdt.net'
password = 'A112358@dp'
from_header = '李德平'
to_header = '客户'
to_address = '528614295@qq.com'


def login_and_send(to_addr: str, message: MIMEMultipart):
    # 开启发信服务，这里使用的是加密传输
    server = smtplib.SMTP_SSL(smtp_server)
    server.connect(smtp_server, 465)
    # 登录发信邮箱
    server.login(from_addr, password)
    # 发送邮件
    server.sendmail(from_addr, to_addr, message.as_string())
    # 关闭服务器
    server.quit()


def send_msg(subject: str, text_content: str, attach_path: str, file_name: str, to_addr=to_address):
    '''发送邮件'''
    # 创建一个带附件的实例
    message = MIMEMultipart()
    message['From'] = Header(from_header, 'utf-8')
    message['To'] = Header(to_header, 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')

    # 邮件正文内容
    message.attach(MIMEText(text_content, 'plain', 'utf-8'))

    # 构造附件1
    att1 = MIMEText(open(attach_path, 'rb').read(), 'base64', 'utf-8')
    att1["Content-Type"] = 'application/octet-stream'
    # 这里的filename可以任意写，写什么名字，邮件中显示什么名字
    att1["Content-Disposition"] = 'attachment; filename="{}"'.format(file_name)
    message.attach(att1)
    login_and_send(to_addr, message)
